package com.hdey.controller.heng;

import com.hdey.pojo.heng.TbUscUser;
import com.hdey.utils.MvcConstant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
//import com.eigpay.supp.general.admin.manager.security.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

//    @RequestMapping("/login")
//    public String login(){
//        return "login";
//    }

    @PostMapping("/login")
    public String home(String name,String pwd){
        UsernamePasswordToken token=new UsernamePasswordToken(name,pwd);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        TbUscUser loginUser= (TbUscUser) subject.getPrincipal();
        subject.getSession().setAttribute("loginUser",loginUser);
        return "redirect:home";
    }


    @ExceptionHandler(Exception.class)
    public String catchException(Exception e){
        System.out.println("进入报错信息");
        System.out.println(e);
        if (e instanceof UnknownAccountException){
            return null;
        }
        return "enter";
    }



//    @ExceptionHandler(ShopNotExistException.class)
//    public ModelAndView catchShopNotExistException(ShopNotExistException ex) {
//        ModelAndView modelAndView = new ModelAndView()
//                .addObject(MvcConstant.ATTR_NAME_EXCEPTION, ex.getMessage());
//        modelAndView.setViewName("forward:/enter.jsp");
//        return modelAndView;
//    }


    @ExceptionHandler(UnknownAccountException.class)
    public ModelAndView catchUnknownAccountException(UnknownAccountException ex) {
        System.out.println("账号不存在");
        ModelAndView modelAndView = new ModelAndView()
                .addObject(MvcConstant.ATTR_NAME_EXCEPTION, "帐号不存在");
        modelAndView.setViewName("redirect:enter");
        return modelAndView;
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    public ModelAndView catchIncorrectCredentialsException(IncorrectCredentialsException ex) {
        System.out.println("密码错误");
        ModelAndView modelAndView = new ModelAndView()
                .addObject(MvcConstant.ATTR_NAME_EXCEPTION, "密码错误");
        modelAndView.setViewName("redirect:enter");
        return modelAndView;
    }
}
